package com.fbt;

import org.springframework.scheduling.annotation.Scheduled;

import java.io.*;
import java.nio.file.*;
import java.util.*;

public class photograph {

    static Integer num = 01;

    static String outputFileName = null;

    public static void main(String[] args) throws IOException {
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
             //   System.out.println("hello world");
                try {
                    generateFoldersAndTransferImages();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, 100, 2000);


    }

    /**
     * 组装
     */

    public static void generateFoldersAndTransferImages() throws IOException {
        System.out.println("    每er秒执行一次  ");
        /**获取到当前文件夹的路径*/
        File folderPath = new File(System.getProperty("user.dir"));
        String readPath = folderPath.getParent();

        //  System.out.println("当前目录 " + folderPath + "   的上一级目录  " + readPath);

        String readPaths[] = {readPath};

        /**读取文件夹中的图片*/

        for (String readPathOne : readPaths) {
            // 获取指定文件夹下所有文件名称
            File file = new File(readPathOne);
            // 获取文件
            List<String> pictureNames = getPictureNames(file);

            //   System.out.println("图片名称" + pictureNames);


            /**将图片导入文件夹中*/

            for (int i = 0; i < pictureNames.size(); i++) {
                String folderName = pictureNames.get(0).replaceAll(".jpg", "");

                String imageName = pictureNames.get(i);

                /**创建新的文件夹*/
                mkDirectory(readPathOne + "\\" + folderName);
                //     System.out.println("在路径  " + readPathOne + "  生产文件夹 " + folderName + "成功");
                outputFileName = readPathOne + "\\" + folderName + "\\";

                fileReadAndWrite(readPathOne, imageName);
            }
        }
    }


    /**
     * 获取文件夹下所有图片名称
     *
     * @param file
     * @return
     */
    public static List<String> getPictureNames(File file) {
        List<String> fileNames = new ArrayList<>();
        //用数组接收
        File files[] = file.listFiles();
        //循环遍历
        for (int i = 0; i < files.length; i++) {
            //获取数组中的第i个
            File fs = files[i];
            if (fs.isDirectory()) {
                //如果是目录就输出

            } else {
                String name = fs.getName();
                // 这里只判断了jpg结尾格式，可自行添加
                if (name.endsWith(".jpg")) {
                    fileNames.add(name);
                } else {
                    //否则直接输出
                    System.out.println(fs.getName());
                }
            }
        }
        return fileNames;
    }

    /**
     * 创建文件夹
     */

    public static boolean mkDirectory(String path) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                return file.mkdirs();
            } else {
                return false;
            }
        } catch (Exception e) {
        } finally {
            file = null;
        }
        return false;
    }

    /**
     * 文件读取及写入
     *
     * @param readPathOne 读取文件路径
     * @param pictureName 图片名称
     * @throws IOException
     */
    public static void fileReadAndWrite(String readPathOne, String pictureName) throws IOException {
        //  System.out.println("读取路径  " + readPathOne + "  图片名字 " + pictureName);
        String filePath = readPathOne + "\\" + pictureName;


        FileInputStream in = new FileInputStream(filePath);

        String outputName = pictureName.replaceAll(".jpg", "");


        String outputPath = outputFileName;
        //  File outputPath = new File("E:\\wsy\\project\\tp\\1");

        System.out.println("输出路径outputPath  " + outputPath);
        FileOutputStream out = new FileOutputStream(outputPath + pictureName);
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
        byte[] by = new byte[1];
        while (bufferedIn.read(by) != -1) {
            bufferedOut.write(by);
        }
        bufferedOut.flush();
        bufferedIn.close();
        bufferedOut.close();
        // 删除原文件夹下文件
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }


    /**
     * 文件监控
     */
    public static void getFile() throws FileNotFoundException, IOException {

        File folderPath = new File(System.getProperty("user.dir"));
        String readPath = folderPath.getParent();

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                WatchKey key;
                try {
                    WatchService watchService = FileSystems.getDefault().newWatchService();
                    Paths.get(readPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
                    int i = 0;
                    while (true) {


                        //   System.out.println("监听的文件夹路径    " + readPath);
                        File file = new File(readPath);//path为监听文件夹
                        File[] files = file.listFiles();
                        System.out.println("等待图片加载！");
                        key = watchService.take();//没有文件增加时，阻塞在这里


                        //     System.out.println("监测没有阻塞");
                        for (WatchEvent<?> event : key.pollEvents()) {
                            System.out.println("  新增几个文件执行几次  ");

                            System.out.println("");
                            generateFoldersAndTransferImages();

                        }

                        i++;
                        System.out.println("执行了   " + i);
                        /*if (!key.reset()) {
                            break; //中断循环
                        }*/
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }, 2000, 3000);//第一个数字2000表示，2000ms以后开启定时器,第二个数字3000，表示3000ms后运行一次run
    }
}
